<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/3/28
 * Time: 上午8:55
 * 余额变动操作
 */

namespace app\common\controller;


use app\common\model\CardCzgive;
use app\common\model\CardCzLog;
use app\common\model\CardMember;
use app\common\model\CardUserBonus;
use app\common\model\CardUserFee;
use app\common\model\CardUserGet;
use app\common\model\CardUserLog;
use app\common\model\CardUserUpdate;
use app\common\model\Paylog;
use think\Controller;
use think\Request;
use Wechat\Wxobjopen;

class Balancet extends Wxoption
{
//    public function _initialize(Request $request)
//    {
//        $param = $request->param();
//        $ActionLogs = new ActionLogs();
//        $ActionLogs->writelog("payos","web","balancet","e:",$param);
//    }
    //余额核销
    public function hx_balance_del(){

    }

    //检查余额
    public function checkbalance($arr,$user,$card){
        $yf_price = $arr['add_balance'];
//        $ActionLogs = new ActionLogs();
//        $ActionLogs->writelog("payos", "web", "cardus/getcardupdate", "2:", $user);
        if ($user['cs_balance'] <> 0) {
            //判断赠送金额是否超过核销金额
            $CardUserGet = new CardUserGet();
            if ($user['cs_balance'] < $arr['add_balance']) {
                //赠送金额归0
                $CardUserGet->where(['id'=>$user['id']])->setField('cs_balance', 0);
                $dedures['del_balance'] = $arr['add_balance']-$user['cs_balance'];                             //实际支付额
            }else{
                $CardUserGet->where(['id'=>$user['id']])->setDec('cs_balance', $arr['add_balance']);
                $dedures['del_balance'] = $arr['add_balance']-$user['cs_balance'];
            }
//            $ActionLogs->writelog("payos", "web", "cardus/getcardupdate", "3:", $dedures);
            $dedures['del_balance'] = '';
            $dedures['dis_card_zk'] = '';                                          //会员折扣
            $dedures['vip_card_zk'] = '';                                               //等级折扣
            $dedures['gel_card_zk'] = '';                                                //卡券折扣
            $dedures['hx_card'] = '';                                                          //要核销的卡券
        } else {
            $CardDedu = new CardDedu();
            $dedures = $CardDedu->getzk($arr,$user,$card);
        }
        $darr['del_balance'] = $dedures['del_balance'];                                                 //实际支付额
        $darr['dis_card_zk'] = $dedures['dis_card_zk'];                                                 //会员折扣
        $darr['vip_card_zk'] = $dedures['vip_card_zk'];                                                 //等级折扣
        $darr['gel_card_zk'] = $dedures['gel_card_zk'];                                                 //卡券折扣
        $darr['hx_card'] = $dedures['hx_card'];                                                          //要核销的卡券
        $darr['yf_balance'] = $yf_price;                                                                  //应付金额
        $darr['add_balance'] = '';
        $darr['pay_balance'] = $arr['add_balance'];                                                         //实际支付额
        return $darr;
    }

    //更新记录 CardUserUpdate
    public function cardupdate($arr,$user,$arrc){
        $datas['code'] = $user['code'];
        $datas['card_id'] = $user['card_id'];
        $datas['openid'] = $user['openid'];
        if (isset($arr['record'])){
            $datas['record_balance'] = $arr['record'];
        }
        $datas['pay_balance'] = $arrc['pay_balance'];
        $datas['add_balance'] = $arrc['add_balance'];
        $datas['mid'] = $arr['mid'];
        if (isset($arr['giveid'])){
            $datas['giveid'] = $arr['giveid'];
        }
        if (isset($arr['del_balance'])){
            $datas['del_balance'] = $arrc['del_balance'];
        }
        if (isset($arr['add_bonus'])) {
            $datas['add_bonus'] = $arr['add_bonus'];
        }
        $datas['con_username'] = $arr['nickname'];
        $datas['hx_fs'] = $arr['hx_fs'];
        $datas['type'] = $arr['type'];
        $datas['cate'] = $arr['cate'];
        $datas['reason'] = $arr['reason'];
        $datas['source'] = $arr['source'];
        $datas['create_time'] = time();
        $CardUserUpdate = new CardUserUpdate();
        $resut = $CardUserUpdate->allowField(true)->save($datas);
//        file_put_contents('/data2/html/payos/rec_user_fee.txt', '0:' . json_encode($datas) . PHP_EOL, FILE_APPEND);
//        file_put_contents('/data2/html/payos/rec_user_fee.txt', '0-0:' . json_encode($user) . PHP_EOL, FILE_APPEND);
        if ($resut){
            //carduserlog记录
            $updataid = $CardUserUpdate->id;
            $datas['up_id'] = $updataid;
            $datas['orderid'] = $arr['orderid'];
            $datas['us_id'] = $user['id'];
            $datas['top_mid'] = $user['top_mid'];
            $datas['mid'] = $user['mid'];
            $datas['nickname'] = $user['nickname'];
//            $this->rec_user_fee($datas);
//            file_put_contents('/data2/html/payos/rec_user_fee.txt', '0-0:' . json_encode($datas) . PHP_EOL, FILE_APPEND);
            $this->rec_user_fee($datas);
//            //有赠送金额时再次新增记录
//            if ($arrc['pay_balance'] < $arrc['add_balance']){
//                $datas['num'] = $arrc['add_balance'] - $arrc['pay_balance'];
//                $datas['cate'] = 2;         //余额
//                $datas['reason'] = 2;         //原因
//                unset($datas['add_bonus']);
//                $r = $this->rec_cardlog($datas);
//            }
        }else{
            $updataid = '';
        }
        return $updataid;
    }

    //增加余额记录
    /*
     *
     *
     */
    public function rec_user_fee($parem){
        try {
            $CardMember = new CardMember();
            $UserBonusFee = new UserBonusFee();
            if (isset($parem['con_username'])){$bonusb['con_username'] = $parem['con_username'];}else{$bonusb['con_username'] = $parem['nickname'];}
            if (isset($parem['record_balance'])){$bonusb['record_balance'] = $parem['record_balance'];}else{$bonusb['record_balance'] = '';}
            $bonusb['us_id'] = $parem['us_id'];
            $bonusb['top_mid'] = $parem['top_mid'];
            $bonusb['mid'] = $parem['mid'];
            $bonusb['c_id'] = $CardMember->where(['card_id' => $parem['card_id']])->value('id');
            $bonusb['openid'] = $parem['openid'];
            $bonusb['card_id'] = $parem['card_id'];
            $bonusb['code'] = $parem['code'];
            $bonusb['pay_cate'] = $parem['hx_fs'];
            $bonusb['balance'] = $parem['pay_balance'];
            $bonusb['type'] = $parem['type'];
            $bonusb['cate'] = 2;
            $bonusb['reason'] = 3;
            $bonusb['source'] = $parem['source'];
            $bonusb['orderid'] = $parem['orderid'];
//            $UserBonusFee->rec_user_fee($bonusb, $parem['type']);
            if ($parem['pay_balance'] < $parem['add_balance']){
                $bonusb['cate'] = 2;
                $bonusb['reason'] = 2;
                $bonusb['balance'] = $parem['add_balance'] - $parem['pay_balance'];
//                $UserBonusFee->rec_user_fee($bonusb, $parem['type']);
            }
        }catch (\Exception $e) {
            $bonusdata = ['code' => 9999, 'message' => $e->getMessage()];
//            file_put_contents('/data2/html/payos/rec_user_fee.txt', '0-1:' . json_encode($bonusdata) . PHP_EOL, FILE_APPEND);
        }
    }

    //更新订单
    public function paylog_rec($arr){
        //订单记录
        $datalog['mid'] = $arr['mid'];                          //mid
        $datalog['orderid'] = $arr['orderid'];     //订单号
        $datalog['pay_statu'] = 1;                              //交易状态
        $datalog['price'] =  $arr['pay_balance'];               //支付金额
        $datalog['pay_time'] = date('Y-m-d H:i:s');     //支付时间
        $datalog['add_time'] = time();                              //支付时间戳
        $datalog['pay_fs'] = $arr['pay_fs'];                                     //支付方式
        //折、抵扣      未加入
        $datalog['openid'] = $arr['openid'];                //会员openid
        //核销时使用
        if ($arr['type'] == 2) {
            $datalog['yf_price'] = $arr['yf_price'];        //应付金额
            $datalog['zk_price'] = $datalog['yf_price'] - $datalog['price'];     //折扣金额
            $datalog['gel_card_zk'] = $arr['gel_card_zk'];          //抵扣金额
            $datalog['vip_card_zk'] = $arr['vip_card_zk'];          //等级折扣金额
            $datalog['dis_card_zk'] = $arr['dis_card_zk'];          //会员折扣金额
            $datalog['hx_card'] = $arr['hx_card'];                   //抵扣卡券
//        $datalog['payinfo'] = '会员卡支付';                      //支付内容
        }
        if ($arr['type'] = 1){
            $datalog['yf_price'] = $arr['pay_balance'];        //应付金额
        }

        if (isset($arr['sub_openid'])){$datalog['sub_openid'] = $arr['sub_openid']; }
        if (isset($arr['pay_cate'])){$datalog['pay_cate'] = $arr['pay_cate']; }
        //END
        $datalog['d_cashier'] = $arr['nickname'];               //操作人
        $Paylog = new Paylog();
        $datalog['oid'] = $Paylog->allowField(true)->save($datalog);
        //更新记录
//        $gx['oid'] = $Paylog->id;
//        $gx['orderid'] = $arr['orderid'];
//        $this->gxbonusfee($gx);
        //END
        $res = $datalog;
        if ($datalog['pay_fs'] == 4){
            $this->isorderdel($datalog);
        }

        //核销卡券
        $CardDedu = new CardDedu();
        $resc = $CardDedu->pay_hx_card($datalog);
        return $res;
    }



    //更新积分/余额记录oid
    private function gxbonusfee($parem){
        $data['oid'] = $parem['oid'];
        $map['orderid'] = $parem['orderid'];
        $CardUserFee = new CardUserFee();
        $CardUserBonus = new CardUserBonus();
        $CardUserFee->save($data,$map);
        $CardUserBonus->save($data,$map);

    }
    //判断上一笔充值状态，并删除该笔
    private function isorderdel($parem){
//        file_put_contents('/data2/html/payos/isorderdel.txt', '0-1:' . json_encode($parem) . PHP_EOL, FILE_APPEND);
        try {
            $Paylog = new Paylog();
            $info = $Paylog->where(['orderid'=>$parem['orderid']])->field('mid,orderid,d_cashier')->find();
            if ($info){
                $page = $Paylog->where(['mid'=>$info['mid'],'d_cashier'=>$info['d_cashier'],'pay_statu'=>1,'pay_fs'=>['in',[2,3]]])->order('id desc')->limit(1)->field('del_statu,orderid')->select();
                if ($page) {
                    $isinfo = $page[0];
                    if ($isinfo['del_statu'] == 0){
                        $gs = $Paylog->allowField(true)->save(['del_statu'=>1],['orderid'=>$isinfo['orderid']]);
                        $del = $Paylog->where(['orderid'=>$parem['orderid']])->delete();
//                        file_put_contents('/data2/html/payos/isorderdel.txt', 'del:' . json_encode($del) . PHP_EOL, FILE_APPEND);
                    }
                }
            }
        }catch (\Exception $e) {
            $bondata = array('code' => 9099, 'message' => $e->getMessage());
        }
    }

    //更新充值记录
    public function cardczlog_rec($datalog,$user,$datas,$arr){
        $czdata['orderid'] = $datalog['orderid'];
        $czdata['openid'] = $user['openid'];
        $czdata['cz_price'] = $datas['pay_balance'];
        $czdata['zs_price'] = $datas['add_balance'] - $datas['pay_balance'];
        $czdata['giveid'] = $arr['giveid'];
        $czdata['statu'] = 1;
        $czdata['code'] = $user['code'];
        $czdata['addtime'] = $datalog['add_time'];
        $CardCzLog = new CardCzLog();
        $resut = $CardCzLog->allowField(true)->save($czdata);
        if ($resut){
            $give_rec_id = $CardCzLog->id;
            return $give_rec_id;
        }
    }

    //冲送判断
    public function cs_type($arr,$user){
        if (!empty($arr['giveid'])) {
            $CardZsgive = new CardCzgive();
            $givetype = $CardZsgive->where(['id'=>$arr['giveid']])->value('type');
//            file_put_contents('/data2/html/payos/regSgive.txt', '0-0:' . json_encode($givetype).PHP_EOL, FILE_APPEND);
            $ComCardPut = new CardPut();
            if ( $givetype == 1 ){
                $arrd['mid'] = $arr['mid'];
                $arrd['top_mid'] = $arr['top_mid'];
                $arrd['giveid'] = $arr['giveid'];
                $arrd['give_rec_id'] = $arr['give_rec_id'];
                $arrd['card_id'] = $user['card_id'];
                $arrd['openid'] = $user['openid'];
                $arrd['nickname'] = $user['nickname'];
                $arrd['code'] = $user['code'];
                $arrd['get_card_id'] = $user['id'];
//                file_put_contents('/data2/html/payos/regSgive.txt', '0:' . json_encode($arrd).PHP_EOL, FILE_APPEND);
                $resut = $ComCardPut->regSgive($arrd);        //新规则，赠送多张
//                $uend['zs_card'] = json_encode($resut['card'],JSON_UNESCAPED_UNICODE);
//                $uend['zs_bonus'] = json_encode($resut['bonus'],JSON_UNESCAPED_UNICODE);
//                file_put_contents('/data2/html/payos/regSgive.txt', '1:' . json_encode($uend).PHP_EOL, FILE_APPEND);
//                $CardUserUpdate = new CardUserUpdate();
//                $res = $CardUserUpdate->where(['id'=>$arr['updataid']])->update($uend);
//                file_put_contents('/data2/html/payos/regSgive.txt', '2:' . json_encode($res).PHP_EOL, FILE_APPEND);
                $res = 1;
            }else {
                //赠送方法
                $sparams['give_rec_id'] = $arr['give_rec_id'];
                $sparams['get_card_id'] = $user['id'];
                $sparams['card_id'] = $user['card_id'];
                $sparams['giveid'] = $arr['giveid'];
                $sparams['openid'] = $user['openid'];
                $sparams['nickname'] = $user['nickname'];
                $sparams['code'] = $user['code'];
                $resut = $ComCardPut->czgive($sparams);       //原规则
//                $uend['zs_card'] = json_encode($resut['card'],JSON_UNESCAPED_UNICODE);
//                $uend['zs_bonus'] = json_encode($resut['bonus'],JSON_UNESCAPED_UNICODE);
                $CardUserUpdate = new CardUserUpdate();
//                $res = $CardUserUpdate->where(['id'=>$arr['updataid']])->update($uend);
                $res = 1;
            }

        }else{
            $res = 1;
        }
        return $res;
    }

    //冲送判断
    public function cs_type_s($arr,$user){
        if (!empty($arr['giveid'])) {
            $CardZsgive = new CardCzgive();
            $givetype = $CardZsgive->where(['id'=>$arr['giveid']])->value('type');
//            file_put_contents('/data2/html/payos/regSgive.txt', '0-0:' . json_encode($givetype).PHP_EOL, FILE_APPEND);
            $ComCardPut = new CardPuttest();
            if ( $givetype == 1 ){
                $arrd['mid'] = $arr['mid'];
                $arrd['top_mid'] = $arr['top_mid'];
                $arrd['giveid'] = $arr['giveid'];
                $arrd['give_rec_id'] = $arr['give_rec_id'];
                $arrd['card_id'] = $user['card_id'];
                $arrd['openid'] = $user['openid'];
                $arrd['nickname'] = $user['nickname'];
                $arrd['code'] = $user['code'];
                $arrd['get_card_id'] = $user['id'];
//                file_put_contents('/data2/html/payos/regSgive.txt', '0:' . json_encode($arrd).PHP_EOL, FILE_APPEND);
                $resut = $ComCardPut->regSgive($arrd);        //新规则，赠送多张
//                $uend['zs_card'] = json_encode($resut['card'],JSON_UNESCAPED_UNICODE);
//                $uend['zs_bonus'] = json_encode($resut['bonus'],JSON_UNESCAPED_UNICODE);
//                file_put_contents('/data2/html/payos/regSgive.txt', '1:' . json_encode($uend).PHP_EOL, FILE_APPEND);
//                $CardUserUpdate = new CardUserUpdate();
//                $res = $CardUserUpdate->where(['id'=>$arr['updataid']])->update($uend);
//                file_put_contents('/data2/html/payos/regSgive.txt', '2:' . json_encode($res).PHP_EOL, FILE_APPEND);
            }else {
                //赠送方法
                $sparams['give_rec_id'] = $arr['give_rec_id'];
                $sparams['get_card_id'] = $user['id'];
                $sparams['card_id'] = $user['card_id'];
                $sparams['giveid'] = $arr['giveid'];
                $sparams['openid'] = $user['openid'];
                $sparams['nickname'] = $user['nickname'];
                $sparams['code'] = $user['code'];
                $resut = $ComCardPut->czgive($sparams);       //原规则
//                $uend['zs_card'] = json_encode($resut['card'],JSON_UNESCAPED_UNICODE);
//                $uend['zs_bonus'] = json_encode($resut['bonus'],JSON_UNESCAPED_UNICODE);
//                $CardUserUpdate = new CardUserUpdate();
//                $res = $CardUserUpdate->where(['id'=>$arr['updataid']])->update($uend);
            }

        }else{
            $res = 1;
        }
        return $res;
    }

    //获取订单号
    private function getorder($sh)
    {
        $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999) . rand(1, 9);
        return $order;
    }


    //余额更新微信操作  系统通知
    public function updatebalance($arr){
        //实例化微信
        $options = $this->options($arr['card_id']);
        $WxObj = new Wxobjopen($options);
        $data = [
            'code'=>$arr['code'],
            'card_id'=>$arr['card_id'],
            'custom_field_value2' => $arr['price'].'元',
            'notify_optional'=>[
                'is_notify_bonus'=>false,
                'is_notify_balance'=>false,
                'is_notify_custom_field2'=>false,
            ],
        ];
        $res = $WxObj->updateUserInfo($data);
        return $res;
    }

    //记录表
    public function rec_cardlog($arr)
    {
        try {
            $CardUserLog = new CardUserLog();
            $data['mid'] = $arr['mid'];
            $data['up_id'] = $arr['up_id'];
            $data['openid'] = $arr['openid'];
            $data['orderid'] = $arr['orderid'];
            $data['con_username'] = $arr['con_username'];
            $data['card_id'] = $arr['card_id'];
            $data['code'] = $arr['code'];
            //是否余额赠送
            if (!isset($arr['num'])) {
                if (isset($arr['pay_balance'])) {
                    if ($arr['type'] == 2) {
                        $data['num'] = -$arr['pay_balance'];
                    } else {
                        $data['num'] = $arr['pay_balance'];
                    }
                }
                if (isset($arr['del_balance'])) {
                    $data['num'] = -$arr['del_balance'];
                }
            }else{
                //赠送余额
                $data['num'] = $arr['num'];
            }
            if (isset($arr['record_balance'])){
                $data['record'] = $arr['record_balance'];           //记录
            }
            $data['type'] = $arr['type'];               //1充值/2核销
            $data['cate'] = $arr['cate'];               //1积分/2余额
            $data['reason'] = $arr['reason'];           //原因
            $data['source'] = $arr['source'];           //来源
            $data['create_time'] = time();
            $res = $CardUserLog->allowField(true)->save($data);
            $ComBonus = new Bonus();
            if (isset($arr['add_bonus'])) {
                $data['add_bonus'] = $arr['add_bonus'];
                $data['cate'] = 1;               //1积分/2余额
                $data['reason'] = 2;           //原因
                $ComBonus->rec_cardlogs($data);
            }

        }catch (\Exception $e) {
            $res = ['errcode' => 9911, 'message' => $e->getMessage()];
        }
        return $res;
    }

}